var app = getApp();
var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var MD5Util = require('../../utils/md5.js'); 

Page({
  data: {
    orderId: 0,
    actualPrice: 0.00,
    orderType:""
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    var transFee = wx.getStorageSync("transFee");
    if(transFee==''||options.needBill!='1'){
      transFee = 0;
    }
    var totalFee = 0;
    if(options.needBill=='1'){
      totalFee = parseFloat(transFee)+parseFloat(options.price)
    }else{
      totalFee = options.price;
    }
    this.setData({
      orderId: options.orderId,
      actualPrice: options.price,
      orderType:options.orderType,
      needBill:options.needBill,
      transFee:transFee,
      totalFee:totalFee
    })
  },
  onReady: function () {

  },
  onShow: function () {
    // 页面显示


  },
  onHide: function () {
    // 页面隐藏

  },
  onUnload: function () {
    // 页面关闭

  },
  //向服务请求支付参数
  requestPayParam(openId,code) {
    let that = this;
    wx.showLoading({
      title: '加载中...',
      mask:true
    })
    util.request(api.PayPrepayId, { orderId: that.data.orderId,openId:openId,code:code,orderType:that.data.orderType}).then(function (res) {
      wx.hideLoading();
      if (res.datas.result) {
        //时间戳
        var timestamp = String(Date.parse(new Date()));
        //从服务器请求回来的参数
        let payParam = res.datas;
        // 按照字段首字母排序组成新字符串
        var payDataA = "appId=" + app.globalData.appId + "&nonceStr=" + payParam.nonceStr + "&package=prepay_id=" + payParam.prepayId + "&signType=MD5&timeStamp=" + timestamp;
        var payDataB = payDataA + "&key=" + app.globalData.key;
        // 使用MD5加密算法计算加密字符串
        var paySign = MD5Util.MD5(payDataB).toUpperCase();
        
        wx.requestPayment({
          'timeStamp': timestamp,
          'nonceStr': payParam.nonceStr,
          'package': "prepay_id="+payParam.prepayId,
          'signType': "MD5",
          'paySign': paySign,
          'success': function (res) {
            wx.redirectTo({
              url: '/pages/payResult/payResult?status=1&orderId=' + that.data.orderId+"&type="+that.data.orderType,
            })
          },
          'fail': function (res) {
            wx.redirectTo({
              url: '/pages/payResult/payResult?status=0&errMsg=' + res.errMsg + "&orderId=" + that.data.orderId+"&type="+that.data.orderType,
            })
          }
        })
      }else{
        wx.showToast({
          title: '支付失败',
        })
      }
    });
  },
  startPay() {
    wx.showLoading({
      title: '请稍候',
      mask:true
    })
    var that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          that.requestPayParam('234', res.code);
        }
      wx.hideLoading()
      }
    });
  }
})